<!DOCTYPE html>
<html lang="en" style="height: 100%">
<head>
  <meta charset="utf-8">
  <style>
    /* 自定义弹窗样式 */
    .dialog-overlay {
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(0,0,0,0.5);
      display: none;
      justify-content: center;
      align-items: center;
      z-index: 9999;
    }
    .dialog-box {
      background: #2c343c;
      padding: 20px;
      border-radius: 5px;
      color: #fff;
      font-family: Arial;
      min-width: 300px;
    }
    .dialog-title {
      font-size: 18px;
      margin-bottom: 15px;
      color: #6ab0ff;
    }
    /* 下拉框样式 */
    .dialog-select {
      width: 100%;
      padding: 8px 30px 8px 12px;
      margin: 10px 0;
      background: #1d2327 url("data:image/svg+xml,%3Csvg...") no-repeat right 10px center;
      border: 1px solid #3a4249;
      color: #fff;
      font-size: 14px;
      appearance: none;
      -webkit-appearance: none;
      border-radius: 3px;
      cursor: pointer;
    }
    
    /* 下拉箭头SVG（精简版） */
    .dialog-select {
      background-image: url("data:image/svg+xml,%3Csvg width='12' height='8' viewBox='0 0 12 8' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M1 1.5L6 6.5L11 1.5' stroke='%23999' stroke-width='2'/%3E%3C/svg%3E");
    }
    
    /* 悬停效果 */
    .dialog-select:hover {
      border-color: #6ab0ff;
    }
    
    /* 聚焦效果 */
    .dialog-select:focus {
      outline: none;
      box-shadow: 0 0 0 2px rgba(106, 176, 255, 0.3);
    }
    
    .dialog-buttons {
      text-align: right;
      margin-top: 15px;
    }
    .dialog-button {
      padding: 6px 15px;
      margin-left: 10px;
      cursor: pointer;
      background: #3a4249;
      border: none;
      color: #fff;
      border-radius: 3px;
    }
    .dialog-button:hover {
      background: #4a5259;
    }
</style>
</head>
<body style="height: 100%; margin: 0">
  <div id="container" style="height: 100%"></div>
  
  <!-- 自定义弹窗 -->
  <div class="dialog-overlay" id="dialogOverlay">
    <div class="dialog-box">
      <div class="dialog-title" id="dialogTitle"></div>
      <select class="dialog-select" id="dialogSelect"> <!-- 添加id属性 -->
        <option value="">请选择</option>
      </select>
      <div class="dialog-buttons">
        <button id="dialogCancel" class="dialog-button">取消</button>
        <button id="dialogConfirm" class="dialog-button">确认</button>
      </div>
    </div>
  </div>

  <script type="text/javascript" src="echarts.js"></script>
  <script type="text/javascript" src="qwebchannel.js"></script>
  <script>
    const dom = document.getElementById('container');
    const myChart = echarts.init(dom, 'dark', { renderer: 'canvas' });
    let seriesDataSet = {}; // 存储来自Qt的数据集
    let maxItems = 6; // 最大动态系列数
    const baseSeriesNames = new Set(['BMS电压请求值', 'BMS电流请求值', '充电机输出电压', '充电机输出电流']);
    
    //接受从Qt来的数据
    var x = [];
    var y = [];
    var webobj; //用于全局给QT发送信息的对象
    var qwebchannel = new QWebChannel(qt.webChannelTransport, function (channel) {
      webobj = channel.objects.webobj;
      window.foo = webobj;
      
      webobj.dataChanged.connect(function (arg) {
        x.push(arg.x);
        y.push(arg.y.toFixed(4));
        myChart.setOption({
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: x
          },
          series: [
            {
              name: 'BMS电压请求值',
              type: 'line',
              smooth: true,
              data: y
            },
            {
              name: 'BMS电流请求值',
              type: 'line',
              smooth: true,
              data: y
            },
            {
              name: '充电机输出电压',
              type: 'line',
              smooth: true,
              data: y
            },
            {
              name: '充电机输出电流',
              type: 'line',
              smooth: true,
              data: y
            }]
          });      
      });
    });
    
    // 初始化基础图表
    function init() {
      myChart.setOption(getBaseOption());
    }

    // 带数据初始化（来自Qt）
    function setQtValue(str) {      
      seriesDataSet = str; // 存储完整数据集
      const option = myChart.getOption();
      
      // 更新轴数据
      option.xAxis[0].data = str.x;
      option.xAxis[1].data = str.x;

      // 更新所有系列数据（包括动态添加的）
      option.series.forEach(series => {
        if (str[series.name]) { // 根据系列名称获取对应数据
          series.data = str.y;
        }
      });

      myChart.setOption(option);
    }

    // 基础配置模板
    function getBaseOption() {
      return {
        title: { text: '基础数据分析' },
        tooltip: { trigger: 'axis' },
        legend: {
          data: ['BMS电压请求值', 'BMS电流请求值', '充电机输出电压', '充电机输出电流']
        },
        grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
        toolbox: {
          show: true,
          feature: {
            dataZoom: { yAxisIndex: 'none' },
            dataView: { readOnly: false },
            //magicType: { type: ['line', 'bar'] },
            //restore: {},
            //saveAsImage: {},
            myAddSeries: {
              show: true,
              title: '添加曲线',
              icon: 'path://M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm192 472c0 4.4-3.6 8-8 8H544v152c0 4.4-3.6 8-8 8h-48c-4.4 0-8-3.6-8-8V544H328c-4.4 0-8-3.6-8-8v-48c0-4.4 3.6-8 8-8h152V328c0-4.4 3.6-8 8-8h48c4.4 0 8 3.6 8 8v152h152c4.4 0 8 3.6 8 8v48z',
              onclick: () => showDialog('添加曲线', [
                    {value: 'BMS最高允许充电总电压', label: 'BMS最高允许充电总电压'},
                    {value: '最高温度', label: '最高温度'},
                    {value: '最低温度', label: '最低温度'}
                  ])
            },
            myToggleVisibility: {
              show: true,
              title: '切换显示',
              icon: 'path://M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm-80 232c-4.4 0-8 3.6-8 8v48c0 4.4 3.6 8 8 8h160c4.4 0 8-3.6 8-8v-48c0-4.4-3.6-8-8-8H432zm0 224c-4.4 0-8 3.6-8 8v48c0 4.4 3.6 8 8 8h160c4.4 0 8-3.6 8-8v-48c0-4.4-3.6-8-8-8H432z',
              onclick: () => showDialog('切换显示', Array.from(myChart.getOption().legend[0].data)
              .map(name =>({
                value: name,
                label: name
              }))
            )
            },
            myDeleteSeries: {
              show: true,
              title: '删除曲线',
              icon: 'path://M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm-80 232c-4.4 0-8 3.6-8 8v48c0 4.4 3.6 8 8 8h160c4.4 0 8-3.6 8-8v-48c0-4.4-3.6-8-8-8H432z',
              onclick: () => showDialog('删除曲线', Array.from(myChart.getOption().legend[0].data)
              .filter(name => !baseSeriesNames.has(name))
              .map(name =>({
                value: name,
                label: name
              }))
              )
            }
          }
        },
        xAxis: [
          { type: 'category', boundaryGap: false, data: [0] },
          { type: 'category', boundaryGap: false, data: [0] }
        ],
        yAxis: { type: 'value' },
        series: baseSeriesNames.size > 0 ? 
          Array.from(baseSeriesNames).map(name => ({
            name: name,
            type: 'line',
            smooth: true,
            data: [0]
          })) : []
      };
    }

    // 显示自定义弹窗
    function showDialog(title, options) {
      webobj.jsCallQt({x: 1, y: 100});
      const overlay = document.getElementById('dialogOverlay');
      const dialogTitle = document.getElementById('dialogTitle');
      const select = document.getElementById('dialogSelect'); // 取消注释
      
      // 清空旧选项
      select.innerHTML = '<option value="">请选择</option>';
      
      // 设置标题
      dialogTitle.textContent = title;
      
      // 动态添加选项（需要真实数据）
      options.forEach(opt => {
          const option = document.createElement('option');
          option.value = opt.value;
          option.textContent = opt.label;
          select.appendChild(option);
      });
      
      overlay.style.display = 'flex';
      select.focus();

      // 清理旧事件
      const confirmBtn = document.getElementById('dialogConfirm');
      const cancelBtn = document.getElementById('dialogCancel');
      confirmBtn.onclick = null;
      cancelBtn.onclick = null;

      // 确认处理
      confirmBtn.onclick = () => {
          const value = select.value;
          overlay.style.display = 'none';
          select.selectedIndex = 0;
          
          if (title === '添加曲线') {
              handleAddSeries(value);
          } else if (title === '切换显示'){
              toggleVisibility(value);
          } else if (title === '删除曲线'){
              deleteSeries(value);
          }
      };

      // 取消处理
      cancelBtn.onclick = () => {
          overlay.style.display = 'none';
          select.selectedIndex = 0;
      };
    }

    // 处理添加系列
    function handleAddSeries(seriesName) {
      if (!seriesName) return;
      
      const option = myChart.getOption();
      if (option.legend[0].data.includes(seriesName)) {
        alert('系列名称已存在！');
        return;
      }

      // 从Qt数据中获取最新数据（示例取最后一个数据点）      
      const newSeries = {
        name: seriesName,
        type: 'line',
        smooth: true,
        data: seriesDataSet[seriesName] || [],
        xAxisIndex: 0
      };

      // 维护系列数量
      if (option.series.length >= maxItems + 4) { // 保留4个基础系列
        const removed = option.series.find(s => !isBaseSeries(s.name));
        option.legend[0].data = option.legend[0].data.filter(n => n !== removed.name);
        option.series = option.series.filter(s => s.name !== removed.name);
      }

      option.series.push(newSeries);
      option.legend[0].data.push(seriesName);
      myChart.setOption(option);
    }

    // 切换显示状态
    function toggleVisibility(seriesName) {
      const option = myChart.getOption();
      if (!option.legend[0].data.includes(seriesName)) return;

      const selected = option.legend[0].selected || {};
      selected[seriesName] = !selected[seriesName];
      myChart.setOption({ legend: { selected } });
    }

    // 处理删除曲线
    function deleteSeries(seriesName) {
      if (!seriesName) return;
      
      const option = myChart.getOption();
      
      // 检查是否基础系列
      if (baseSeriesNames.has(seriesName)) {
        alert('基础系列不可删除！');
        return;
      }

      // 检查是否存在
      if (!option.legend[0].data.includes(seriesName)) {
        alert('未找到指定曲线！');
        return;
      }

      // 执行删除，series移除不掉
      // option.legend[0].data = option.legend[0].data.filter(n => n !== seriesName);
      // option.series = option.series.filter(s => s.name !== seriesName);
      
      // myChart.setOption(option);

      // 执行删除
      const newOption = {
        legend: [{
          data: option.legend[0].data.filter(n => n !== seriesName)
        }],
        series: option.series.filter(s => s.name !== seriesName)
      };

      // 关键修改：使用 replaceMerge 强制替换系列数据
      myChart.setOption(newOption, { replaceMerge: ['series'] });
    }

    // 判断是否基础系列
    function isBaseSeries(name) {
      const baseNames = ['BMS电压请求值', 'BMS电流请求值', '充电机输出电压', '充电机输出电流'];
      return baseNames.includes(name);
    }

    // 初始化图表
    init();
    window.addEventListener('resize', myChart.resize);
  </script>
</body>
</html>